import mongoose, { Document, Schema } from 'mongoose';

export interface INotification extends Document {
  recipient: mongoose.Types.ObjectId; // 接收者
  sender?: mongoose.Types.ObjectId; // 发送者（系统通知可能没有）
  type: 'lesson_published' | 'lesson_liked' | 'comment_received' | 'system';
  title: string;
  content: string;
  relatedModel?: 'LessonPlan' | 'Comment' | 'User';
  relatedId?: mongoose.Types.ObjectId;
  isRead: boolean;
  readAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const notificationSchema = new Schema<INotification>({
  recipient: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true
  },
  sender: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  type: {
    type: String,
    enum: ['lesson_published', 'lesson_liked', 'comment_received', 'system'],
    required: true
  },
  title: {
    type: String,
    required: true,
    maxlength: 200
  },
  content: {
    type: String,
    required: true,
    maxlength: 500
  },
  relatedModel: {
    type: String,
    enum: ['LessonPlan', 'Comment', 'User']
  },
  relatedId: {
    type: Schema.Types.ObjectId
  },
  isRead: {
    type: Boolean,
    default: false,
    index: true
  },
  readAt: {
    type: Date
  }
}, {
  timestamps: true
});

// 复合索引优化查询
notificationSchema.index({ recipient: 1, isRead: 1, createdAt: -1 });
notificationSchema.index({ recipient: 1, createdAt: -1 });

export const Notification = mongoose.model<INotification>('Notification', notificationSchema);